package net.vinote.smart.platform.service.handler;

import java.sql.SQLException;

import net.vinote.smart.platform.comm.StringFunction;
import net.vinote.smart.platform.module.database.DBManager;
import net.vinote.smart.platform.module.database.DBManagerFactory;
import net.vinote.smart.platform.module.database.DBTransaction;
import net.vinote.smart.platform.module.database.bo.BizObject;
import net.vinote.smart.platform.service.GeneralTools;
import net.vinote.smart.platform.service.dw.handler.CommonHandler;
import net.vinote.smart.platform.service.dw.handler.HandlerPerimissionAnnotation;
import net.vinote.smart.platform.service.util.Permission;
import net.vinote.smart.platform.service.util.Permission.PermissionEnum;

/**
 * 用户密码修改handler
 * 
 * @author 郑俊伟
 * 
 */
@HandlerPerimissionAnnotation(
		insert = @Permission(PermissionEnum.SMART_USER_INFO_INSERT),
		update = @Permission(PermissionEnum.SMART_USER_INFO_UPDATE),
		delete = @Permission(PermissionEnum.SMART_USER_INFO_DELETE),
		query = @Permission(PermissionEnum.SMART_USER_INFO_QUERY))
public class UserPasswordChangeHandler extends CommonHandler {

	@Override
	public void initDisplayForEdit(BizObject bo) {
		bo.setAttribute("PassWord", "");
	}

	@Override
	protected void beforeUpdate(BizObject bo, DBTransaction tx) {
		encodePassword(bo);
	}

	protected void afterUpdate(BizObject bo, DBTransaction tx) {
		decodePassword(bo);
	}

	private void encodePassword(BizObject bo) {
		bo.setAttribute(
				"PassWord",
				GeneralTools.encrypt(bo.getAttribute("PassWord"),
						GeneralTools.getAesKey(bo.getAttribute("UserID"))));
	}

	private void decodePassword(BizObject bo) {
		bo.setAttribute(
				"PassWord",
				GeneralTools.decrypt(bo.getAttribute("PassWord"),
						GeneralTools.getAesKey(bo.getAttribute("UserID"))));
	}

	@Override
	protected boolean validityCheck(BizObject bo, boolean isInsert) {
		if (isInsert) {
			error = "不支持保存";
			return false;
		}
		String userID = bo.getAttribute("userID");
		String oldPwd = bo.getAttribute("oldPassword");
		DBManager bm = DBManagerFactory.getInstance("user_info");
		try {
			BizObject userBo = bm
					.createQuery(new String[] { "password" }, "userid=?")
					.setParamVal(userID).getSingleResult();
			if (userBo == null) {
				error = "用户名:" + userID + "不存在!";
				return false;
			}
			if (!GeneralTools.encrypt(oldPwd, GeneralTools.getAesKey(userID))
					.equals(userBo.getAttribute("password"))) {
				error = "原密码输入错误!";
				return false;
			}

			if (StringFunction.nullToBlank(bo.getAttribute("PassWord")).trim()
					.length() == 0) {
				error = "密码不能为空";
				return false;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return true;
	}
}
